/**
 * 中华非遗渲染器
 * 负责将数据动态渲染成HTML
 * 
 * @author 中华非遗团队
 * @version 1.0.0
 * @date 2024
 */

/**
 * 主页卡片布局渲染器
 * 渲染认识非遗页面上半部分的卡片布局
 */
class HeritageMainRenderer {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        this.data = HeritageDataAPI.getMainData();
    }

    /**
     * 渲染所有分类
     */
    render() {
        if (!this.container) {
            console.error('Main container not found');
            return;
        }

        this.container.innerHTML = '';
        
        this.data.forEach((category, index) => {
            const categoryElement = this.createCategoryElement(category, index);
            this.container.appendChild(categoryElement);
        });

        // 重新初始化交互功能
        this.initializeInteractions();
    }

    /**
     * 创建分类元素
     */
    createCategoryElement(category, index) {
        const section = document.createElement('div');
        section.className = 'category-section';
        section.setAttribute('data-category', category.categoryName);
        section.style.animationDelay = `${index * 0.1}s`;

        section.innerHTML = `
            <h3 class="category-title ${category.categoryClass}">
                ${category.categoryName}
            </h3>
            <div class="heritage-grid">
                ${category.items.map(item => this.createItemHTML(item)).join('')}
            </div>
        `;

        return section;
    }

    /**
     * 创建项目HTML
     */
    createItemHTML(item) {
        const clickAction = item.clickAction ? 
            `onclick="window.location.href='${item.clickAction}'" style="cursor: pointer;"` : '';

        return `
            <div class="heritage-card" data-keywords="${item.keywords}" ${clickAction}>
                <div class="card-image">
                    <img src="${item.image}" alt="${item.title}" class="heritage-img">
                </div>
                <div class="card-content">
                    <h4>${item.title}</h4>
                    <p>${item.description}</p>
                    <div class="card-tags">
                        ${item.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 初始化交互功能
     */
    initializeInteractions() {
        // 这里可以添加一些交互功能，比如卡片点击效果等
        const cards = this.container.querySelectorAll('.heritage-card');
        cards.forEach(card => {
            card.addEventListener('mouseenter', this.onCardHover);
            card.addEventListener('mouseleave', this.onCardLeave);
        });
    }

    /**
     * 卡片悬停事件
     */
    onCardHover(event) {
        // 可以添加悬停效果
    }

    /**
     * 卡片离开事件
     */
    onCardLeave(event) {
        // 可以添加离开效果
    }
}

/**
 * 扩展内容渲染器
 * 渲染显示更多按钮展开的内容
 */
class HeritageExtendedRenderer {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        this.data = HeritageDataAPI.getExtendedData();
    }

    /**
     * 渲染扩展内容
     */
    render() {
        if (!this.container) {
            console.error('Extended container not found');
            return;
        }

        const layoutContainer = this.container.querySelector('.heritage-list-layout');
        if (!layoutContainer) {
            console.error('Layout container not found');
            return;
        }

        layoutContainer.innerHTML = '';
        
        this.data.forEach((category, index) => {
            const categoryElement = this.createExtendedCategoryElement(category, index);
            layoutContainer.appendChild(categoryElement);
        });

        // 重新初始化滚动功能
        this.initializeScrolling();
    }

    /**
     * 创建扩展分类元素
     */
    createExtendedCategoryElement(category, index) {
        const categoryDiv = document.createElement('div');
        categoryDiv.className = 'heritage-list-category';
        categoryDiv.style.animationDelay = `${(index + 1) * 0.1}s`;

        categoryDiv.innerHTML = `
            <div class="category-header-list">
                <div class="category-icon-wrapper ${category.categoryClass}">
                    <i class="${category.categoryIcon}"></i>
                </div>
                <div class="category-info">
                    <h3>${category.categoryName}</h3>
                    <p>${category.description}</p>
                </div>
                <div class="category-count">
                    <span>${category.itemCount}项</span>
                </div>
            </div>
            <div class="heritage-list-items">
                ${category.items.map(item => this.createExtendedItemHTML(item)).join('')}
            </div>
        `;

        return categoryDiv;
    }

    /**
     * 创建扩展项目HTML
     */
    createExtendedItemHTML(item) {
        const clickAction = item.clickAction ? 
            `onclick="window.location.href='${item.clickAction}'" style="cursor: pointer;"` : '';

        return `
            <div class="heritage-list-item" ${clickAction}>
                <div class="item-thumbnail">
                    <img src="${item.image}" alt="${item.title}">
                    <div class="item-overlay">
                        <i class="fas fa-eye"></i>
                    </div>
                </div>
                <div class="item-details">
                    <h4>${item.title}</h4>
                    <p>${item.description}</p>
                    <div class="item-meta">
                        ${item.metaTags.map(tag => `<span class="meta-tag">${tag}</span>`).join('')}
                        <span class="meta-date">${item.metaDate}</span>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 初始化滚动功能
     */
    initializeScrolling() {
        const scrollContainers = document.querySelectorAll('.heritage-list-items');
        
        scrollContainers.forEach(container => {
            // 添加触摸支持（移动端）
            let startX = 0;
            let scrollStartLeft = 0;
            
            container.addEventListener('touchstart', (e) => {
                startX = e.touches[0].clientX;
                scrollStartLeft = container.scrollLeft;
            });
            
            container.addEventListener('touchmove', (e) => {
                if (!startX) return;
                
                const x = e.touches[0].clientX;
                const diff = startX - x;
                container.scrollLeft = scrollStartLeft + diff;
            });
            
            container.addEventListener('touchend', () => {
                startX = 0;
                scrollStartLeft = 0;
            });
            
            // 鼠标滚轮支持（桌面端）
            container.addEventListener('wheel', (e) => {
                e.preventDefault();
                container.scrollLeft += e.deltaY;
            });
        });
    }
}

/**
 * 搜索建议渲染器
 */
class SearchSuggestionsRenderer {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        this.data = HeritageDataAPI.getSearchSuggestions();
    }

    /**
     * 渲染搜索建议
     */
    render() {
        if (!this.container) {
            console.error('Search suggestions container not found');
            return;
        }

        this.container.innerHTML = '';
        
        this.data.forEach(suggestion => {
            const suggestionElement = this.createSuggestionElement(suggestion);
            this.container.appendChild(suggestionElement);
        });

        // 添加点击事件
        this.initializeSuggestionClicks();
    }

    /**
     * 创建建议元素
     */
    createSuggestionElement(suggestion) {
        const div = document.createElement('div');
        div.className = 'suggestion-item';
        div.setAttribute('data-category', suggestion.category);
        div.textContent = suggestion.category;
        return div;
    }

    /**
     * 初始化建议点击事件
     */
    initializeSuggestionClicks() {
        const suggestions = this.container.querySelectorAll('.suggestion-item');
        suggestions.forEach(suggestion => {
            suggestion.addEventListener('click', () => {
                const category = suggestion.getAttribute('data-category');
                const searchInput = document.getElementById('heritageSearch');
                if (searchInput) {
                    searchInput.value = category;
                    // 触发搜索
                    if (typeof performSearch === 'function') {
                        performSearch();
                    }
                }
            });
        });
    }
}

/**
 * 搜索结果渲染器
 */
class SearchResultsRenderer {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
    }

    /**
     * 渲染搜索结果
     */
    render(results, query) {
        if (!this.container) {
            console.error('Search results container not found');
            return;
        }

        this.container.innerHTML = '';

        // 合并搜索结果
        const allResults = [...results.main, ...results.extended];

        if (allResults.length === 0) {
            this.renderNoResults();
            return;
        }

        allResults.forEach(result => {
            const resultElement = this.createResultElement(result);
            this.container.appendChild(resultElement);
        });
    }

    /**
     * 创建搜索结果元素
     */
    createResultElement(result) {
        const { category, item } = result;
        
        // 检查是否是扩展数据（有metaTags）
        const isExtended = item.hasOwnProperty('metaTags');
        
        if (isExtended) {
            // 转换为卡片格式显示
            return this.createCardFromExtendedItem(item);
        } else {
            // 直接使用原始卡片格式
            return this.createCardFromMainItem(item);
        }
    }

    /**
     * 从主页数据创建卡片
     */
    createCardFromMainItem(item) {
        const div = document.createElement('div');
        div.className = 'heritage-card';
        
        const clickAction = item.clickAction ? 
            `onclick="window.location.href='${item.clickAction}'" style="cursor: pointer;"` : '';

        div.innerHTML = `
            <div class="card-image">
                <img src="${item.image}" alt="${item.title}" class="heritage-img">
            </div>
            <div class="card-content">
                <h4>${item.title}</h4>
                <p>${item.description}</p>
                <div class="card-tags">
                    ${item.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                </div>
            </div>
        `;

        if (item.clickAction) {
            div.style.cursor = 'pointer';
            div.onclick = () => window.location.href = item.clickAction;
        }

        return div;
    }

    /**
     * 从扩展数据创建卡片
     */
    createCardFromExtendedItem(item) {
        const div = document.createElement('div');
        div.className = 'heritage-card';

        div.innerHTML = `
            <div class="card-image">
                <img src="${item.image}" alt="${item.title}" class="heritage-img">
            </div>
            <div class="card-content">
                <h4>${item.title}</h4>
                <p>${item.description}</p>
                <div class="card-tags">
                    ${item.metaTags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                </div>
            </div>
        `;

        if (item.clickAction) {
            div.style.cursor = 'pointer';
            div.onclick = () => window.location.href = item.clickAction;
        }

        return div;
    }

    /**
     * 渲染无结果页面
     */
    renderNoResults() {
        this.container.innerHTML = `
            <div class="no-results-message">
                <i class="fas fa-search"></i>
                <h3>未找到相关结果</h3>
                <p>请尝试使用其他关键词搜索</p>
            </div>
        `;
    }
}

/**
 * 全局渲染管理器
 * 统一管理所有渲染器
 */
class HeritageRenderManager {
    constructor() {
        this.mainRenderer = null;
        this.extendedRenderer = null;
        this.searchSuggestionsRenderer = null;
        this.searchResultsRenderer = null;
    }

    /**
     * 初始化所有渲染器
     */
    init() {
        // 初始化主页渲染器
        this.mainRenderer = new HeritageMainRenderer('categoryWrapper');
        
        // 初始化扩展内容渲染器
        this.extendedRenderer = new HeritageExtendedRenderer('moreContentSection');
        
        // 初始化搜索建议渲染器
        this.searchSuggestionsRenderer = new SearchSuggestionsRenderer('searchSuggestions');
        
        // 初始化搜索结果渲染器
        this.searchResultsRenderer = new SearchResultsRenderer('resultsContainer');
    }

    /**
     * 渲染所有内容
     */
    renderAll() {
        try {
            if (this.mainRenderer) {
                this.mainRenderer.render();
            }
            
            if (this.extendedRenderer) {
                this.extendedRenderer.render();
            }
            
            if (this.searchSuggestionsRenderer) {
                this.searchSuggestionsRenderer.render();
            }
            
            console.log('所有内容渲染完成');
        } catch (error) {
            console.error('渲染过程中发生错误:', error);
        }
    }

    /**
     * 执行搜索并渲染结果
     */
    performSearch(query) {
        if (!query.trim()) {
            this.showAllContent();
            this.hideSearchResults();
            return;
        }

        const results = HeritageDataAPI.search(query);
        
        if (this.searchResultsRenderer) {
            this.searchResultsRenderer.render(results, query);
        }
        
        this.hideAllContent();
        this.showSearchResults();
    }

    /**
     * 显示所有内容
     */
    showAllContent() {
        const mainCategories = document.querySelector('.heritage-categories');
        const moreContent = document.getElementById('moreContentSection');
        
        if (mainCategories) mainCategories.style.display = 'block';
        if (moreContent && moreContent.classList.contains('active')) {
            moreContent.style.display = 'block';
        }
    }

    /**
     * 隐藏所有内容
     */
    hideAllContent() {
        const mainCategories = document.querySelector('.heritage-categories');
        const moreContent = document.getElementById('moreContentSection');
        
        if (mainCategories) mainCategories.style.display = 'none';
        if (moreContent) moreContent.style.display = 'none';
    }

    /**
     * 显示搜索结果
     */
    showSearchResults() {
        const searchResults = document.getElementById('searchResults');
        if (searchResults) {
            searchResults.style.display = 'block';
        }
    }

    /**
     * 隐藏搜索结果
     */
    hideSearchResults() {
        const searchResults = document.getElementById('searchResults');
        if (searchResults) {
            searchResults.style.display = 'none';
        }
    }
}

// 全局渲染管理器实例
window.heritageRenderManager = new HeritageRenderManager();

// 导出类（兼容不同的模块系统）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        HeritageMainRenderer,
        HeritageExtendedRenderer,
        SearchSuggestionsRenderer,
        SearchResultsRenderer,
        HeritageRenderManager
    };
} 